package main

import (
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/funlake/gopkg/utils/log"
	"github.com/garyburd/redigo/redis"
	"os"
	_ "pq/routers"
	"time"
)
func main() {
	go func() {
		pwd := os.Getenv("PQ_REDIS_PASSWORD")
		pool := &redis.Pool{
			MaxIdle:     50,
			MaxActive:   150,
			IdleTimeout: 100 * time.Second,
			Wait:        false,
			Dial: func() (redis.Conn, error) {
				c, err := redis.Dial("tcp", fmt.Sprintf("%s:%s",os.Getenv("PQ_REDIS_HOST"),os.Getenv("PQ_REDIS_PORT")))
				if err != nil {
					log.Error(err.Error())
					return nil, err
				}
				if pwd != "" {
					if _, err := c.Do("AUTH", pwd); err != nil {
						log.Error(err.Error())
						_ = c.Close()
						return nil, err
					}
				}
				// 选择db
				_, _ = c.Do("SELECT", 0)
				log.Success("Init one redis connection")
				return c, nil
			},
		}
		sub := redis.PubSubConn{Conn:pool.Get()}
		_ = sub.PSubscribe("after_submit")
		log.Info("Redis subscribe start")
		for{
			switch v := sub.Receive().(type) {
			case redis.PMessage:
				var data map[string]interface{}
				_ = json.Unmarshal(v.Data, &data)
				log.Info("%v",data)
			case redis.Message:
				log.Info(string(v.Data))
			case error:
				log.Error("redis subscribe error:"+v.Error())
			default:
				//log.Info("what the fuck!?")
			
			}
		}
		log.Info("Redis subscribe done","")
	}()
	beego.Run()

}

